package cn.itcast.ui;

import cn.itcast.entity.User;

import javax.swing.*;
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.Objects;

/**
 * 登录成功后--主菜单界面
 */
public class MenuFrame extends JFrame {
    private static final long serialVersionUID = -1796834130339697339L;

    private ClientContext clientContext;

    public MenuFrame() {
        init();
    }

    public void setClientContext(ClientContext clientContext) {
        this.clientContext = clientContext;
    }

    private void init() {
        setTitle("传智考试系统");
        setSize(600, 400);
        setContentPane(createContentPane());
        setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
        addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                clientContext.exit(MenuFrame.this);
            }
        });
    }

    private JPanel createContentPane() {
        JPanel pane = new JPanel(new BorderLayout());

        ImageIcon icon = new ImageIcon(
                Objects.requireNonNull(getClass().getResource("logo.gif")));
        pane.add(BorderLayout.NORTH, new JLabel(icon));

        pane.add(BorderLayout.CENTER, createMenuPane());

        pane.add(BorderLayout.SOUTH,
                new JLabel("版权所有 盗版必究",
                        JLabel.RIGHT));

        return pane;
    }

    private JPanel createMenuPane() {
        JPanel pane = new JPanel(new BorderLayout());
        //务必将info 引用到界面控件对象
        info =
                new JLabel("XXX 同学您好!", JLabel.CENTER);

        pane.add(BorderLayout.NORTH, info);
        pane.add(BorderLayout.CENTER, createBtnPane());

        return pane;
    }

    private JPanel createBtnPane() {
        JPanel pane = new JPanel(new FlowLayout());
        JButton start = createImgBtn("exam.png", "开始");
        JButton result = createImgBtn("result.png", "分数");
        JButton msg = createImgBtn("message.png", "考试规则");
        JButton exit = createImgBtn("exit.png", "离开");

        pane.add(start);
        pane.add(result);
        pane.add(msg);
        pane.add(exit);

        start.addActionListener(e -> clientContext.start());
        result.addActionListener(e -> clientContext.result());
        exit.addActionListener(e -> clientContext.exit(MenuFrame.this));

        return pane;
    }

    private JButton createImgBtn(
            String img, String txt) {
        ImageIcon ico = new ImageIcon(
                Objects.requireNonNull(getClass().getResource(img)));

        JButton button = new JButton(txt, ico);
        button.setVerticalTextPosition(
                JButton.BOTTOM);
        button.setHorizontalTextPosition(
                JButton.CENTER);

        return button;
    }

    ////务必将info 引用到界面控件对象
    private JLabel info;

    public void updateView(User user) {
        String str = "欢迎 【" + user + "】 参加考试!";
        info.setText(str);
    }

}
